package WebRoot.users;

import java.util.HashMap;
import java.util.Map;

import org.hoyi.DB.CLuster.DataBaseCluster;
import org.hoyi.DB.Interface.IDatabase;
import org.hoyi.DB.ctrl.Console;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.district.DistrictCtrls;
import org.hoyi.district.disctrictType;
import org.hoyi.nosql.RedisCtrls;
import org.hoyi.util.DateTimeUtil;
import org.hoyi.util.HoyiExceptUtils;

import model.users;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

public class userService extends Hoyipage{
	
	public void LOADDEF() {
		int ret = DistrictCtrls.Load_DEF_ENTS("user", users.class, disctrictType.BALANCE_LOAD);
		this.HandlerEx("load success!~", ret);
	}

	public void readconfig() {
		String tmpcount = DistrictCtrls.ReadConfig("user", users.class);
		this.WriteUTF8HTML(tmpcount);
	}
	
	public void adduser() {
		// 根据用户分区类型，获取到执行操作的database.
		IDatabase tbs = DistrictCtrls.get_Insert_DB("user", users.class);
		users _us = new users(tbs.Get_Clust_UUID(), "randomuser", "1", DateTimeUtil.getCurrentDateTime(), "");
		int ret = _us.Insert(tbs);

		this.HandlerEx("添加用户", ret);
	}
	
	/**
	 * 单区删除
	 */
	public void deleteuser() {
		String uxid = this.getParams("uxid");
		String cluster_key = DistrictCtrls.GetClustKey(uxid);
		
		IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", cluster_key);
		int ret = users.E().Where(users.uxid.Equals(uxid)).Delete(_tdb);
		
		this.HandlerEx("删除用户", ret);
	}
	
	/**
	 * 全区删除.
	 */
	public void deletealldisuser() {
		String username = this.getParams("username");
		// 循环每个区，修改username为username的用户type 为13
		int rret = 0;
		for (String clus_keys : DataBaseCluster.clusters.get("user").keySet()) {
			IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", clus_keys);

			int ret = users.E().Where(users.username.Equals(username)).Delete(_tdb);
			rret += ret;
		}
		this.HandlerEx("ret=" + rret + ",删除全区用户数据", rret);
	}
	
	/**
	 * 单区修改.
	 */
	public void updateuser() {
		String uxid = this.getParams("uxid");
		String cluster_key = DistrictCtrls.GetClustKey(uxid);
		
		IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", cluster_key);
		users _users = users.E().Where(users.uxid.Equals(uxid)).First(_tdb);
		_users.setUsertype("3");
		int ret  = _users.UpdateD(_tdb);
		
		this.HandlerEx("更新用户", ret);
	}
	
	/**
	 * 全区修改.
	 */
	public void updatealluser() {
		String username = this.getParams("username");
		// 循环每个区，修改username为username的用户type 为13
		int rret = 0;
		for (String clus_keys : DataBaseCluster.clusters.get("user").keySet()) {
			IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", clus_keys);

			int ret = users.E().Where(users.username.Equals(username)).Update(_tdb, users.usertype.SET("13"));
			rret += ret;
		}
		this.HandlerEx("ret=" + rret + ",修改全区用户数据", rret);
	}
	
	/**
	 * 查找(配置)
	 */
	public void LCountCONFIG() {
		String username = this.getParams("username");
		// 循环每个区，修改username为username的用户type 为13
		long lcount = 0;
		Jedis _jJedis = RedisCtrls.getJedis();
		for (String clus_keys : DataBaseCluster.clusters.get("user").keySet()) {
			
			String lcos = _jJedis.get(DistrictCtrls.Get_ENT_COUNT_KEY("user", clus_keys, users.class));
			long ret = Long.valueOf(lcos);
			lcount += ret;
		}
		RedisCtrls.returnResource(_jJedis);
		this.WriteUTF8HTML("lcount=" + lcount );
	}
	
	/**
	 * Count(全区)
	 */
	public void LCount() {
		String username = this.getParams("username");
		// 循环每个区，修改username为username的用户type 为13
		long lcount = 0;
		for (String clus_keys : DataBaseCluster.clusters.get("user").keySet()) {
			IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", clus_keys);

			long ret = users.E().LongCount(_tdb);
			lcount += ret;
		}
		this.WriteUTF8HTML("lcount=" + lcount );
	}
	
	public void Select() {
		String username = this.getParams("username");
		int pagesize = 2;
		//String pgidx = this.getParams("pgidx"); 
		long startidx = Integer.parseInt(this.getParams("startidx"));
		long endidx = Integer.parseInt(this.getParams("endidx"));
		
		// 每个区的满足条件的条数.
		Map<String, Long> cfil_counts = new HashMap<String, Long>();
		
		for (String clus_keys : DataBaseCluster.clusters.get("user").keySet()) {
			IDatabase _tdb = DataBaseCluster.Get_WRITE_SERVER("user", clus_keys);

			long ret = users.E().Where(users.username.Equals(username)).LongCount(_tdb);
			// 这些条件可以存在数据库内，5秒内相同的KEY，不用重复存储.
			
			cfil_counts.put(clus_keys, ret);
		}
		
		long starttmp = 0;
		long endtmp = 0;
		
		String start_clus_key_id = "";
		long start_start;  // 
		long start_end;
		
		String end_clus_key_id = "";
		long end_start;
		long end_end;
		
		boolean start_geted = false;
		boolean end_geted = false;
		
		for (String clus_keys : cfil_counts.keySet()) {
			
			starttmp += cfil_counts.get(clus_keys);
			endtmp += cfil_counts.get(clus_keys);
			
			if(startidx <= starttmp && !start_geted) {
				startidx = starttmp;
				start_clus_key_id = clus_keys; // 这个正确.
				start_geted = true;
			}
			
			if(endidx <= endtmp && !end_geted) {
				endidx = endtmp;
				end_clus_key_id = clus_keys; // 这个正确.
				end_geted = true;
			}
			
			Console.Info("starttmp:" + endtmp + ", endtmp: " + endtmp);
			Console.Info("startidx:" + startidx + ", endidx: " + endidx);
			
			// 得到的应该
			// 开始的集群KEY， 开始idx, 结束idx
			// 结束的集群KEY， 开始idx, 结束idx
			
			if(start_geted && end_geted)
				break;
		}
		
		if(!end_geted) {
			endidx = endtmp;
			end_clus_key_id = (String) cfil_counts.keySet().toArray()[cfil_counts.size() - 1];
		}
		
		this.WriteUTF8HTML("cfil_counts:" + cfil_counts + ", start_clus_KEY:" + start_clus_key_id + "   , end_clus_KEY:" + end_clus_key_id + "<br />" + "startidx:" + startidx + ", endidx:" + endidx);
	}
	
	public void Count() {
		int count = users.E().Count();
		this.WriteUTF8JSONDATAMSG(100, "counts", count);
		
		DataBaseCluster.Get_READ_SERVER("user", "c1");
	}
	
	public void getuserById() {
		String userid = this.getParams("userid");
		users _users = users.E().Where(users.userid.Equals(userid)).First();
		JSONObject _obj = JSONObject.fromObject(_users);
		
		this.WriteUTF8HTML(_obj.toString());
	}
	
	public void Demo() {
		IDatabase dbs = DataBaseCluster.Get_Transaction_WRITE_SERVER();
		int ret = 0;
		try {
			users _user = new users("XX", "", "1", DateTimeUtil.getCurrentDateTime(), "");
			ret = _user.Insert(dbs);

			if(ret != 1) {
				HoyiExceptUtils.NEWS().ThrowException(500, "XX错误!~");
			}
			
			users _userx = new users("XX", "", "1", DateTimeUtil.getCurrentDateTime(), "");
			ret = _userx.Insert(dbs);
			
			dbs.CommitTranscation();
		} catch (Exception e) {
			// TODO: handle exception
			dbs.RollBackTransaction();
			ret = -1;
		}
		this.HandlerEx("测试", ret);
	}
	
	// 简单的话，还是一个项目都链接所有的集群，然后处理的时候拿database放进去，最简单？那样的话，就读集群这里要做个修改.
	
	// 多个项目就涉及到远程调用的问题，
	
}













